<template>
  <div class="ma-content-block lg:flex justify-between p-4">
    <!-- CRUD 组件 -->
    <ma-crud :options="options" :columns="columns" ref="crudRef">
      <template #tableAfterButtons>
        <!-- <a-button type="primary" @click="loadMachinePosition()">
          <template #icon>
            <icon-cloud-download />
          </template>

<template #default>加载位置数据</template>
</a-button> -->
        <!-- <a-button>后置扩展操作B</a-button> -->
      </template>
      <template #warn_point="{ record }">
        <a-link  status="success" v-if="record.warn_point" style="font-size:12px;">是报警点</a-link>
        <br>
        <a-tag checkable color="red"  v-if="record.warn_point">值为：{{ record.warn_point }}</a-tag>
      </template>
      <template #operationBeforeExtend="{ record }">


        <a-link @click="setWarnPoint(record)" status="warning">
          <template #icon>
            <icon-settings />
          </template>
          设置报警点
        </a-link>

        <a-link @click="getWarnPoint(record)" status="primary" v-if="record.warn_point">
          <template #icon>
            <icon-settings />
          </template>
          查看预警数据
        </a-link>
      </template>
 
      <template #operationCell="{ record }">

        <a-popconfirm content="你确定要删除该标注点吗？" @ok="deletePosition(record)">
          <a-button type="text" status="danger" size="small">
            <template #icon>
              <icon-delete />
            </template>
            <!-- Use the default slot to avoid extra spaces -->
            <template #default>删除</template>
          </a-button>
        </a-popconfirm>

      </template>
      <!-- 排序列 -->
      <template #sort="{ record }">
        <a-input-number :default-value="record.sort" mode="button" @change="changeSort($event, record.id)" :min="0"
          :max="1000" />
      </template>
    </ma-crud>
  </div>
  <a-modal v-model:visible="visible" title="设置报警点" @cancel="handleCancel" @before-ok="handleBeforeOk"
    @ok="handelWarnPoint">
    <a-form :model="form">
      <a-form-item field="warn_point" label="防区编码">
        <a-input v-model="form.warn_point" />
      </a-form-item>
    </a-form>
  </a-modal>
  <device-warn-home ref="deviceWarnHomeRef"  />
</template>
<script setup> 
import { ref, reactive, onMounted, onUnmounted, watch } from 'vue'
import systemDevicePosition from '@/api/system/systemDevicePosition'
import { Message } from '@arco-design/web-vue'
import tool from '@/utils/tool'
import * as common from '@/utils/common'
import DeviceWarnHome from '@/views/system/deviceWarn/home.vue'
const crudRef = ref()
const props = defineProps(["client", "curDevieInfo", "case_id", "isDelete"]);
const topic = ref();
const current_position_id = ref(0)
const visible = ref(false);
const deviceWarnHomeRef = ref()
const form = reactive({
  warn_point: ''

});

topic.value = "PERSONDEVICE/" + props.curDevieInfo.device_num
const generateUniqueKey = () => {
  let key = 'key_';
  const time = Date.now().toString(36);
  const random = Math.random().toString(36).substr(2, 9);
  return key + time + random;
}

console.log(props.curDevieInfo)
console.log(props.client)
onMounted(() => {


})
onUnmounted(() => {

})
watch(() => props.isDelete, (newVal, oldVal) => {
  console.log(`count 变化了，新值: ${newVal}, 旧值: ${oldVal}`);
  crudRef.value.refresh()
});

//设置报警点
const setWarnPoint = (record) => {
  visible.value = true;
  current_position_id.value = record.id
}

//查看预警数据

const getWarnPoint = (record)=>{
  deviceWarnHomeRef.value.open(record)

}
const handleBeforeOk = (done) => {
  console.log(form)
  if (form.warn_point == '') {
    Message.warning("请填写报警点值")
    return false
  }
  window.setTimeout(() => {
    done()
    // prevent close
    // done(false)
  }, 2000)
};
const handleCancel = () => {
  visible.value = false;
}

const handelWarnPoint = (record)=>{
  systemDevicePosition.update(current_position_id.value,{warn_point:form.warn_point }).then(res => {
   
    crudRef.value.refresh()
    res.success && Message.success(res.message)
  }).catch(e => { console.log(e) })

}
//删除点位标注
const deletePosition = (record) => {
  let message_id = generateUniqueKey();
  loadOrderResult(JSON.stringify({ order: "machine@cmd@delete_position", params: { pname: record.name }, message_id: message_id, remark: "delete_position" }), "获取地图标定位置", "delete_position", message_id)
  props.client.publish(topic.value, JSON.stringify({ order: "machine@cmd@delete_position", params: { pname: record.name }, message_id: message_id, remark: "delete_position" }));
  Message.loading("正在删除标定位置..")
}

const loadOrderResult = (order_name, name, remark, message_id) => {

  let orderArr = {
    name: name,
    order_name: order_name,
    created_at: tool.dateFormat(new Date),
    device_num: props.curDevieInfo.device_num,
    message_id: message_id,
    remark: remark,
    order_result: "",
    isload: 2
  }
}
// 加载机器人位置数据
const loadMachinePosition = () => {

  let message_id = generateUniqueKey();
  loadOrderResult(JSON.stringify({ order: "machine@reeman@position", message_id: message_id, remark: "position" }), "获取地图标定位置", "position", message_id)
  props.client.publish(topic.value, JSON.stringify({ order: "machine@reeman@position", message_id: message_id, remark: "position" }));
  Message.loading("获取地图标定位置..")
  setTimeout(() => {
    console.log("refresh")
    crudRef.value.refresh()
  }, 2000)

}
const numberOperation = (newValue, id, numberName) => {
  systemDevicePosition.numberOperation({ id, numberName, numberValue: newValue }).then(res => {
    res.success && Message.success(res.message)
  }).catch(e => { console.log(e) })
}

const switchStatus = (statusValue, id, statusName) => {
  systemDevicePosition.changeStatus({ id, statusName, statusValue }).then(res => {
    res.success && Message.success(res.message)
  }).catch(e => { console.log(e) })
}


const options = reactive({

  beforeRequest: params => {
    // 指定排序字段为浏览量字段
    params.device_num = props.curDevieInfo.device_num

    params.case_id = props.case_id ? props.case_id : 0

  },

  id: 'system_device_position',
  rowSelection: {
    showCheckedAll: true
  },
  pk: 'id',
  operationColumn: true,
  operationWidth: 160,
  formOption: {
    viewType: 'modal',
    width: 600
  },
  api: systemDevicePosition.getList,
  recycleApi: systemDevicePosition.getRecycleList,
  add: {
    show: false,
    api: systemDevicePosition.save,
    auth: ['system:devicePosition:save']
  },
  edit: {
    show: false,
    api: systemDevicePosition.update,
    auth: ['system:devicePosition:update']
  },
  delete: {
    show: true,
    api: systemDevicePosition.deletes,
    auth: ['system:devicePosition:delete'],
    realApi: systemDevicePosition.realDeletes,
    realAuth: ['system:devicePosition:realDeletes']
  },
  recovery: {
    show: false,
    api: systemDevicePosition.recoverys,
    auth: ['system:devicePosition:recovery']
  },
  import: {
    show: false,
    url: 'system/devicePosition/import',
    templateUrl: 'system/devicePosition/downloadTemplate',
    auth: ['system:devicePosition:import']
  },
  export: {
    show: false,
    url: 'system/devicePosition/export',
    auth: ['system:devicePosition:export']
  }
})
const changeSort = async (value, id) => {

  const response = await systemDevicePosition.numberOperation({ id, numberName: 'sort', numberValue: value })
  if (response.success) {
    Message.success(response.message)
  }
}
const columns = reactive([
  {
    title: "",
    dataIndex: "id",
    formType: "input",
    addDisplay: false,
    editDisplay: false,
    hide: true,
    commonRules: {
      required: true,
      message: "请输入"
    }
  },
  {
    title: "设备编码",
    dataIndex: "device_num",
    formType: "input",
    search: false,
    hide: true
  },
  {
    title: "位置名称",
    dataIndex: "name",
    formType: "input",
    search: true
  },
  {
    title: '排序', dataIndex: 'sort', formType: 'input-number', addDefaultValue: 1, width: 180,
    min: 0, max: 1000,
  },
  {
    title: "点位类型",
    dataIndex: "type",
    formType: "select",
    search: true,
    multiple: false,
    dict: {
      data: [
        {
          label: "配送点",
          value: "delivery"
        },
        {
          label: "路线点",
          value: "normal"
        },
        {
          label: "出品点",
          value: "production"
        },
        {
          label: "充电桩",
          value: "charge"
        }
      ],
      translation: true
    }
  },
  {
    title: "防区编号",
    dataIndex: "warn_point",
    formType: "input",
    addDisplay: false,
    editDisplay: true
  },
  {
    title: "坐标点",
    dataIndex: "pose",
    formType: "input",
    addDisplay: false,
    editDisplay: true
  },
  {
    title: "web坐标",
    dataIndex: "web_pose",
    formType: "input",
    addDisplay: false,
    editDisplay: true
  },
  {
    title: "所属点位",
    dataIndex: "point_id",
    formType: "input",
    search: false,
    addDisplay: false,
    editDisplay: false,
    hide: true
  },
  {
    title: "巡航方案",
    dataIndex: "case_id",
    formType: "input",
    search: false,
    addDisplay: false,
    editDisplay: false,
    hide: true
  },
  {
    title: "创建时间",
    dataIndex: "created_at",
    formType: "date",
    addDisplay: false,
    editDisplay: false,
    hide: true,
    showTime: true
  },
  {
    title: "更新时间",
    dataIndex: "updated_at",
    formType: "date",
    addDisplay: false,
    editDisplay: false,
    hide: true,
    showTime: true
  },
  {
    title: "删除时间",
    dataIndex: "deleted_at",
    formType: "date",
    addDisplay: false,
    editDisplay: false,
    hide: true,
    showTime: true
  },
  {
    title: "创建者",
    dataIndex: "created_by",
    formType: "input",
    addDisplay: false,
    editDisplay: false,
    hide: true
  },
  {
    title: "更新者",
    dataIndex: "updated_by",
    formType: "input",
    addDisplay: false,
    editDisplay: false,
    hide: true
  },
  {
    title: "所属区域",
    dataIndex: "dept_id",
    formType: "input",
    search: false,
    addDisplay: false,
    editDisplay: false,
    hide: true
  }
])
</script>
<script>export default { name: 'system:devicePosition' } </script>


<style scoped>
::deep(.arco-col .arco-form-item-label-col .arco-form-item-label-col-flex) {
  width: 90px !important;

}
</style>